import axios from 'axios'
import { getFromStorage, logoutClear } from './index'

const service = axios.create({
  // baseURL: 'http://119.3.197.191/',
  timeout: 2 * 60 * 1000
})


service.interceptors.request.use(
  async config => {
    try {
      const HRMS_TOKEN = await getFromStorage("HRMS_TOKEN")
      if(HRMS_TOKEN){
        config.headers["X-Access-Token"] = HRMS_TOKEN
      }
    } catch (error) {
      console.error(error)
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    if (response.status === 200) {
      if(response.data.code === 200){
        if(response.config.headers && response.config.headers.withFullResponse){
          return response.data
        }
        return response.data.result
      }else{
        console.error(response.data.message || 'Server side error.')
        Promise.reject()
      }
    } else {
      Promise.reject()
    }
  },
  error => {
    console.log('axios response error: >>', error)
    console.log('error?.response?.data?.message: >>', error?.response?.data?.message)
    if(error?.response?.data?.message && error?.response?.data?.message.includes('Token失效')){
      logoutClear()
      window.location.reload()
    }
    return Promise.reject(error)
  }
)

export default service